package com.nulldev.util.web.soundcloud;

import com.nulldev.util.lang.json.Json;
import com.nulldev.util.lang.json.JsonObject;
import com.nulldev.util.string.StringsUtil;
import com.nulldev.util.uri.URIUtil;
import com.nulldev.util.uri.Soup_imported.Jsoup;
import com.nulldev.util.uri.Soup_imported.nodes.Document;
import com.nulldev.util.uri.Soup_imported.nodes.Element;

public class SoundcloudExtractor {
	/*
	 * CLIENT_ID required
	 * sourced from 
	 * 
	 * Stream JSON URL: 
	 * https://api.soundcloud.com/i1/tracks/<track_id>/streams?client_id=<client_id>
	 */
	
	public static JsonObject getTracks(final String clientID, final String trackID) {
		try {
			final String URL = "https://api.soundcloud.com/i1/tracks/" + trackID + "/streams?client_id=" + clientID;
			return Json.parse(
					URIUtil.downloadPage(URIUtil.safeCreate(URL))
					).asObject();
		}catch (Exception e) {
			final JsonObject out = Json.object();
			out.add("error", "Invalid client ID!");
			return out;
		}
	}
	
	public static String getAPIKey(final String songURL) throws Exception {
		if (!songURL.contains("soundcloud.com/")) {
			return null;
		}
		final String data0 = URIUtil.downloadPage(URIUtil.safeCreate(songURL));
		final Document doc0 = Jsoup.parse(data0);
		String clientIDURL = null;
		for (final Element e : doc0.getElementsByTag("script")) {
			final String src = e.attr("src");
			if (src != null && src.startsWith("https://a-v2.sndcdn.com/assets/app-")) {
				clientIDURL = src;
				break;
			}
		}
		if (clientIDURL == null) {
			return null;
		}
		final String data = URIUtil.downloadPage(URIUtil.safeCreate(clientIDURL));
		final String clientID = StringsUtil.substringBetween(data, "{client_id:\"", "\"}},");
		return clientID;
	}
	
	public static String getTrackID(final String songURL) throws Exception {
		if (!songURL.contains("soundcloud.com/")) {
			return null;
		}
		final String data0 = URIUtil.downloadPage(URIUtil.safeCreate(songURL));
		String trackID = StringsUtil.substringBetween(data0, "\"urn\":\"soundcloud:tracks:", "\"},\"");
		if (trackID.contains("\",")) {
			return trackID.substring(0, trackID.indexOf("\","));
		}
		return trackID;
	}
	
	public static String getMP3URL(final JsonObject obj) {
		if (obj == null) {
			return null;
		}
		return obj.getString("http_mp3_128_url");
	}
	
	public static void main(final String[] args) throws Exception {
		final String URL = "https://soundcloud.com/occultlabel/coffee-break";
		final String cID = getAPIKey(URL);
		final String tID = getTrackID(URL);
		System.out.println("Client ID: " + cID);
		System.out.println("Track ID: " + tID);
		final JsonObject out = getTracks(cID, tID);
		System.out.println(getMP3URL(out));
	}
}
